{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['add_audio',\n",
       " 'add_custom_scalars',\n",
       " 'add_custom_scalars_marginchart',\n",
       " 'add_custom_scalars_multilinechart',\n",
       " 'add_embedding',\n",
       " 'add_figure',\n",
       " 'add_graph',\n",
       " 'add_histogram',\n",
       " 'add_image',\n",
       " 'add_image_with_boxes',\n",
       " 'add_images',\n",
       " 'add_onnx_graph',\n",
       " 'add_pr_curve',\n",
       " 'add_pr_curve_raw',\n",
       " 'add_scalar',\n",
       " 'add_scalars',\n",
       " 'add_text',\n",
       " 'add_video',\n",
       " 'all_writers',\n",
       " 'caffe2_enabled',\n",
       " 'close',\n",
       " 'default_bins',\n",
       " 'export_scalars_to_json',\n",
       " 'file_writer',\n",
       " 'log_dir',\n",
       " 'scalar_dict']"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import torch\n",
    "import torchvision.utils as vutils\n",
    "import numpy as np\n",
    "import torchvision.models as models\n",
    "from torchvision import datasets\n",
    "from tensorboardX import SummaryWriter\n",
    "import datetime\n",
    "writer = SummaryWriter()\n",
    "#有以下可用的方法\n",
    "list(filter(lambda x:False if x.startswith(\"_\") else True ,dir(writer)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 添加标量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "#二十个step对应的损失\n",
    "losses = [1.3,1.23,1.19,1.1,1.098,1.02,0.98,0.87,0.67,0.43,0.23,0.12,0.12,0.109,0.09,0.0009,0.005,0.0006,0.00064,0.00006]\n",
    "for step in range(20):\n",
    "    #add_scalar方法将信息写入日志文件\n",
    "    writer.add_scalar(\"data/loss\",losses[step],step)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 可视化图片"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "#数据加载\n",
    "from torchvision.datasets import ImageFolder\n",
    "from torchvision import transforms,utils,models,datasets\n",
    "simple_transform = transforms.Compose([transforms.Resize((120,120))\n",
    "                                       ,transforms.ToTensor()\n",
    "                                       #,transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n",
    "                                      ])\n",
    "train_data = ImageFolder('../chapter4/DogVsCatData/train',simple_transform)\n",
    "to_image = transforms.ToPILImage()\n",
    "for i in range(8):\n",
    "    writer.add_image(\"data/Dog_Cat_Image_{}\".format(i),train_data[i][0],i)\n",
    "    writer.add_image_with_boxes('data/Dog_Cat_Image_with_box_{}'.format(i), train_data[i][0], \n",
    "                                torch.Tensor([[10, 10,100, 100]]), i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 添加音频"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(3):\n",
    "    writer.add_audio(\"audio/audio_{}\".format(i),train_data[i][0].view(-1),i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 普通文本"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(2):\n",
    "    writer.add_text('Text/Simple_Text', 'text logged at step:{}'.format(i), i)\n",
    "    writer.add_text('Text/Markdown_Text', '''a|b\\n-|-\\nc|d''',i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### PR精度召回率曲线"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [],
   "source": [
    "writer.add_pr_curve('精度召回率曲线', np.random.randint(2, size=100), np.random.rand(100), 10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [],
   "source": [
    "true_positive_counts = [75, 64, 21, 5, 0]\n",
    "false_positive_counts = [150, 105, 18, 0, 0]\n",
    "true_negative_counts = [0, 45, 132, 150, 150]\n",
    "false_negative_counts = [0, 11, 54, 70, 75]\n",
    "precision = [0.3333333, 0.3786982, 0.5384616, 1.0, 0.0]\n",
    "recall = [1.0, 0.8533334, 0.28, 0.0666667, 0.0]\n",
    "\n",
    "writer.add_pr_curve_raw('精度召回率曲线原始数据', true_positive_counts,\n",
    "                                false_positive_counts,\n",
    "                                true_negative_counts,\n",
    "                                false_negative_counts,\n",
    "                                precision,\n",
    "                                recall, 10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on method add_pr_curve in module tensorboardX.writer:\n",
      "\n",
      "add_pr_curve(tag, labels, predictions, global_step=None, num_thresholds=127, weights=None, walltime=None) method of tensorboardX.writer.SummaryWriter instance\n",
      "    Adds precision recall curve.\n",
      "    \n",
      "    Args:\n",
      "        tag (string): Data identifier\n",
      "        labels (torch.Tensor, numpy.array, or string/blobname): Ground truth data. Binary label for each element.\n",
      "        predictions (torch.Tensor, numpy.array, or string/blobname):\n",
      "        The probability that an element be classified as true. Value should in [0, 1]\n",
      "        global_step (int): Global step value to record\n",
      "        num_thresholds (int): Number of thresholds used to draw the curve.\n",
      "        walltime (float): Optional override default walltime (time.time()) of event\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(writer.add_pr_curve)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 导出数据到json文件，以便外部程序处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [],
   "source": [
    "writer.export_scalars_to_json(\"./all_scalars.json\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 降维投影"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "warning: Embedding dir exists, did you set global_step for add_embedding()?\n",
      "warning: Embedding dir exists, did you set global_step for add_embedding()?\n"
     ]
    }
   ],
   "source": [
    "dataset = datasets.MNIST('mnist', train=False, download=True)\n",
    "images = dataset.test_data[:1000].float()\n",
    "labels = dataset.test_labels[:1000]\n",
    "features = images.view(1000, 784)\n",
    "writer.add_embedding(features, metadata=labels, label_img=images.unsqueeze(1))\n",
    "writer.add_embedding(features, global_step=1, tag='noMetadata')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "writer.close()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
